# Generates, signs and imports the server certificate to a keystore
echo -e "..::::: SERVER :::::..\n"

mkdir server
cd server

CERT_PASSWORD=password
STORE_PASSWORD=password
CA_CERT_PASSWORD=password

# Create a server keypair that is stored in a keystore
keytool -genkeypair -alias server -dname "cn=server" -keypass $CERT_PASSWORD -keystore keystore -storepass $STORE_PASSWORD

# Create a CSR (Certificate Signing Request)
keytool -certreq -alias server -file server_req.csr -keystore keystore -storepass $STORE_PASSWORD

# Sign the CSR with the CA
openssl x509 -req -passin pass:$CA_CERT_PASSWORD -in server_req.csr -CA ../ca/cacert.pem -CAkey ../ca/privkey.pem -CAserial ../ca/ca.srl -out server_signed.cer

# Import the CA to the keystore
keytool -importcert -alias ca -file ../ca/cacert.pem -keystore keystore -storepass $STORE_PASSWORD -noprompt

# Import the certificate chain to the keystore
keytool -importcert -trustcacerts -alias server -file server_signed.cer -keystore keystore -storepass $STORE_PASSWORD

# Verify that a certificate chain has been established
keytool -list -v -keystore keystore -storepass $STORE_PASSWORD

cd ..
